package Network

import (
	"SQL/myDB"
)

//确定添加群成员：
//s groupID string,[memeberIDs string]
//r Message string,
//  nil
func addGroupMember(userID string, data dy_judge) (code int, msg string, result interface{}) {
	code, msg, groupID := data.judgeID("groupID")
	if code != Success {
		return
	}
	code, msg = IsGroupManager(userID, groupID)
	if code != Success {
		return
	}
	code, msg, memberID := data.judgeMemberIDs("memberIDs")
	if code != Success {
		return
	}
	code, msg = canAddGroupMember(groupID, len(memberID))
	if code != Success {
		return
	}

	return dealAddGroupMember(groupID, memberID)
}

func dealAddGroupMember(groupID string, memberID []string) (code int, msg string, result interface{}) {
	db := openDB()
	defer closeDB(db)

	tx, err := db.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()

	err = myDB.TxExecMultiSql(tx, "insert into members(groupID,userID,isManager) values($2,$1,false)", memberID, groupID)
	if err != nil {
		code = errDBExecFailed
		msg = err.Error()
		return
	}

	err = tx.Commit()
	if err != nil {
		code = errEndTx
		msg = err.Error()
		return
	}

	return Success, "", nil
}
